package handler

import (
	"github.com/gin-gonic/gin"
	"life/api/request"
	"life/internal/dao"
	"life/internal/model"
	"log"
	"net/http"
	"path"
)

func UploadFile(c *gin.Context) {

	// 单文件
	file, _ := c.FormFile("file")
	log.Println(file.Filename)
	ext := path.Ext(file.Filename)
	if ext != ".jpg" && ext != "png" {
		c.JSON(http.StatusOK, gin.H{
			"code":    1000,
			"message": "格式类型不正确",
			"data":    nil,
		})
		return
	}

	dst := "./static/" + file.Filename
	// 上传文件至指定的完整文件路径
	err := c.SaveUploadedFile(file, dst)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    1000,
			"message": "上传失败",
			"data":    nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    1000,
		"message": "上传成功",
		"data":    dst,
	})

}

func AddCreate(c *gin.Context) {
	form, _ := c.MultipartForm()
	files := form.File["files"]

	if len(files) > 9 {
		c.JSON(http.StatusOK, gin.H{
			"code":    1000,
			"message": "最多只能上传9个文件",
			"data":    nil,
		})
		return
	}

	for _, file := range files {
		log.Println(file.Filename)

		ext := path.Ext(file.Filename)
		if ext != ".jpg" && ext != ".png" && ext != ".mp4" {
			c.JSON(http.StatusOK, gin.H{
				"code":    1000,
				"message": "格式类型不正确",
				"data":    nil,
			})
			return
		}

		dst := "./static/" + file.Filename
		// 上传文件至指定的完整文件路径
		err := c.SaveUploadedFile(file, dst)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code":    1000,
				"message": "上传失败",
				"data":    nil,
			})
			return
		}
	}
	var req request.AddArticle
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    1000,
			"message": "未接收参数",
			"data":    nil,
		})
		return
	}

	data := model.Article{
		Title:   req.Title,
		Context: req.Context,
	}
	dao.Create(&data)

	if data.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    1000,
			"message": "发布失败",
			"data":    nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    1000,
		"message": "发布成功",
		"data":    data,
	})
}
